<?php
// +----------------------------------------------------------------------
// | Fengli [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://www.yanyongwang.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 风黎 < 1280246895@qq.com >
// +----------------------------------------------------------------------
/**
 * 文件上传控制器
 * Author:闫永旺
 * 1280246895@qq.com
 */

namespace app\admin\controller;

use OSS\OssClient;
use OSS\Core\OssException;
use think\Controller;
use think\Db;
use think\Session;

class Upload extends Controller{
    //阿里Oss账户信息
    protected         $accessKeyId;                         //阿里云账号AccessKey
    protected         $accessKeySecret;                     //阿里云账号AccessKeySecret
    protected         $endpoint;                            // EndPoint（地域节点）
    protected         $bucket;                              // 存储空间名称


    /**
     * 构造函数  执行
     */
    public function __construct()
    {
        //暂时写死 账户信息 以后改为存储数据库中
        $this->accessKeyId              = "";
        $this->accessKeySecret          = "";
        $this->endpoint                 = "";
        $this->bucket                   = "";
    }

    public function upload($module='admin',$use='admin_thumb')
    {
        //TODO 后台设置文件上传配置  本地上传   阿里oss上传  或者其他三方上传
        //先本与学习先默认直接使用阿里oss文件上传
        if(request()->file('file')){
            $file               = request()->file('file');
        }else{
            $res['code']        = 1;
            $res['msg']         = '没有上传文件';
            return json($res);
        }

        $ext                    = pathinfo($file->getInfo()['name'],PATHINFO_EXTENSION);        //文件后缀名
        $filePath               = $file->getPathname();                                                 //文件绝对路径路径
        $fileName               = md5(time()) .'.'. $ext;                                               //保存文件名
        $res                    = $this->aliOssFileUpload($module,$use,$fileName,$filePath);            // 上传阿里云OSS并保存数据库 得到数据库信息
        return $res;
    }
    function gmt_iso8601($time) {
        $dtStr = date("c", $time);
        $mydatetime = new DateTime($dtStr);
        $expiration = $mydatetime->format(DateTime::ISO8601);
        $pos = strpos($expiration, '+');
        $expiration = substr($expiration, 0, $pos);
        return $expiration."Z";
    }
    /**
     * 阿里oss上传 签名验证
     */
    public function getAliOssInfo()
    {


         $id= '6MKOqxGiGU4AUk44';
         $key= 'ufu7nS8kS59awNihtjSonMETLI0KLy';
         $host = 'http://post-test.oss-cn-hangzhou.aliyuncs.com';
         $dir = 'user-dir/';


        $now = time();
        $expire = 30; //设置该policy超时时间是10s. 即这个policy过了这个有效时间，将不能访问
        $end = $now + $expire;
        $expiration = gmt_iso8601($end);



        //最大文件大小.用户可以自己设置
        $condition = array(0=>'content-length-range', 1=>0, 2=>1048576000);
        $conditions[] = $condition;

        //表示用户上传的数据,必须是以$dir开始, 不然上传会失败,这一步不是必须项,只是为了安全起见,防止用户通过policy上传到别人的目录
        $start = array(0=>'starts-with', 1=>'$key', 2=>$dir);
        $conditions[] = $start;


        $arr = array('expiration'=>$expiration,'conditions'=>$conditions);

        $policy = json_encode($arr);
        $base64_policy = base64_encode($policy);
        $string_to_sign = $base64_policy;
        $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $key, true));

        $response = array();
        $response['accessid'] = $id;
        $response['host'] = $host;
        $response['policy'] = $base64_policy;
        $response['signature'] = $signature;
        $response['expire'] = $end;
        //这个参数是设置用户上传指定的前缀
        $response['dir'] = $dir;
        return json_encode($response);
    }


    /**
     * 本地上传图片方法
     * @return [type] [description]
     */
    public function localUpload($module='admin',$use='admin_thumb',$file)
    {

        $module                 = $this->request->has('module') ? $this->request->param('module') : $module;//模块
        $web_config             = Db::name('webconfig')->where('web','web')->find();
        $info                   = $file->validate(['size'=>$web_config['file_size']*1024,'ext'=>$web_config['file_type']])->rule('date')->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . $module . DS . $use);
        if($info) {
            //写入到附件表
            $data               = [];
            $data['module']     = $module;
            $data['filename']   = $info->getFilename();                             //文件名
            $data['filepath']   = DS . 'uploads' . DS . $module . DS . $use . DS . $info->getSaveName();//文件路径
            $data['fileext']    = $info->getExtension();                            //文件后缀
            $data['filesize']   = $info->getSize();                                 //文件大小
            $data['create_time']= time();                                           //时间
            $data['uploadip']   = request()->ip();                                  //IP
            $data['user_id']    = Session::has('admin') ? Session::get('admin') : 0;
            $data['save_type']  = 1;                                                //1 =本地储存 2= 阿里oss 3=七牛云 ...
            if($data['module']  = 'admin') {
                //通过后台上传的文件直接审核通过
                $data['status']     = 1;
                $data['admin_id']   = $data['user_id'];
                $data['audit_time'] = time();
            }
            $data['use']        = $this->request->has('use') ? $this->request->param('use') : $use;//用处
            $res['id']          = Db::name('attachment')->insertGetId($data);
            $res['src']         = DS . 'uploads' . DS . $module . DS . $use . DS . $info->getSaveName();
            $res['code']        = 2;
            $res['msg']         = "上传成功";
            addlog($res['id']);                     //记录日志
            return $res;
        } else {
            // 上传失败获取错误信息
            return $this->error('上传失败：'.$file->getError());
        }
    }

    /**
     * 阿里OSS存储  字符串流上传  字符串流不能上传图片
     * @param array $fileName 文件名称
     * @param string $content 文件内容
     * return array
     */
    public function aliOssStrUpload()
    {
        // 文件名称
        $fileName = "a.txt";
        // 文件内容
       $content = "hello word";
        try{
            $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);

            $data      = $ossClient->putObject($this->bucket, $fileName, $content);

        } catch(OssException $e) {
            printf(__FUNCTION__ . ": FAILED\n");
            printf($e->getMessage() . "\n");
            return;
        }
        print(__FUNCTION__ . ": OK" . "\n");
    }

    /**
     * 阿里OSS存储  文件流上传
     * @param string $fileName 文件名称
     * @param string $filePath 本地文件路径加文件名包括后缀
     * return array
     */
    public function aliOssFileUpload($module='admin',$use='admin_thumb',$fileName,$filePath)
    {
        // 文件名称
        $fileName               = $fileName;
        // <yourLocalFile>由本地文件路径加文件名包括后缀组成，例如/users/local/myfile.txt
        $filePath               = $filePath;

        try{
            $ossClient          = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);

            $result             = $ossClient->uploadFile($this->bucket, $fileName, $filePath);      //阿里OSS返回结果集

            $data               = [];
            $data['module']     = $module;
            $data['filename']   = $fileName;                                        //文件名
            $data['filepath']   = $result['info']['url'];                           //文件路径
            $data['fileext']    = pathinfo($fileName,PATHINFO_EXTENSION);   //文件后缀
            $data['filesize']   = $result['info']['size_upload'];                   //文件大小
            $data['create_time']= time();                                           //时间
            $data['uploadip']   = $result['info']['local_ip'];                      //IP
            $data['user_id']    = Session::has('admin') ? Session::get('admin') : 0;
            $data['save_type']  = 2;                                                //1 =本地储存 2= 阿里oss 3=七牛云 ...
            if($data['module']  = 'admin') {
                //通过后台上传的文件直接审核通过
                $data['status']     = 1;
                $data['admin_id']   = $data['user_id'];
                $data['audit_time'] = time();
            }
            $data['use']        = request()->has('use') ? request()->has('use') : $use;//用处
            $res['id']          = Db::name('attachment')->insertGetId($data);
            $res['src']         = $result['info']['url'];
            $res['code']        = 2;
            $res['msg']         = "上传成功";

            return $res;

        } catch(OssException $e) {
            return $e->getMessage();    //返回错误信息
        }
    }

    /**
     * 阿里OSS 删除多个文件
     * @param array $fileName 要删除的文件名称数组
     * return array
     */
    public function aliOssDelete()
    {
        // 文件名称
        $fileName = "a.png";

        try{
            $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);

            $data      = $ossClient->deleteObjects($this->bucket, $fileName);
            halt($data);
        } catch(OssException $e) {
            printf(__FUNCTION__ . ": FAILED\n");
            printf($e->getMessage() . "\n");
            return;
        }
        print(__FUNCTION__ . ": OK" . "\n");
    }
}